package channel;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

import stream.Stream;
import weibo4j.Status;
import weibo4j.Weibo;
import weibo4j.WeiboException;


public class ChannelTimedoutWeibo implements Channel {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	
	static public final int TYPE = TIMEDOUTWEIBO;
	
	public static void main(String[] args) throws WeiboException, InterruptedException {
		ChannelTimedoutWeibo channelTimedoutWeibo = new ChannelTimedoutWeibo();
		channelTimedoutWeibo.setTargetScreenName("CincyHuang");
		channelTimedoutWeibo.setDeadline(new Date());
		Thread.sleep(5000);
		
		System.out.println(channelTimedoutWeibo.THIS());
	}
	
	private String key;						//this
	
	private String targetScreenName;		//this
	
	private Date beginTime = new Date();	//this
	private Date deadline;					//this
	
	public ChannelTimedoutWeibo() throws WeiboException {
		this.key = "";
	}
	
	public ChannelTimedoutWeibo(String targetScreenName, Date deadline) throws WeiboException {
		this.targetScreenName = targetScreenName;
		this.key = "";
		this.deadline = deadline;
	}
	
	public ChannelTimedoutWeibo(String targetScreenName, Date deadline, 
						 String key) throws WeiboException {
		this.targetScreenName = targetScreenName;
		this.key = key;
		this.deadline = deadline;
	}
	
	
	@SuppressWarnings("finally")
	@Override
	public int THIS() {
		int res = 0;
		
		try {
			res = timedoutToGetTargetWeibo() ? 1 : 0;
			
		} catch (WeiboException e) {
			res = 0;
			e.printStackTrace();
			
		} finally {
			return res;
		}
	}

	@Override
	public void THAT() {
		
	}
	
	
	private boolean timedoutToGetTargetWeibo() throws WeiboException {
		
		Date now = new Date();
		if ( deadline.before(now) &&
			 now.getTime() - deadline.getTime() < task.TaskState.TIME_INTERVAL ) {

			List<Status> status = Weibo.getInstance(TRIGGER_ADDRESS, TRIGGER_PASSWORD).
									getUserTimeline(targetScreenName);
			
			for (Status s : status) {
				Date sendDate = s.getCreatedAt();
				if ( sendDate.after(beginTime) &&
					 s.getText().contains(key) ) {
					return false;
				}
			}
			return true;
		}
		return false;

	}
	
	public void setKey(String key) {
		this.key = key;
	}

	public void setTargetScreenName(String targetScreenName) throws WeiboException {
		this.targetScreenName = targetScreenName;
	}
	
	public void setDeadline(Date deadline) {
		this.deadline = deadline;
	}
	
	public void setbeginTime(Date beginTime) {
		this.beginTime = beginTime;
	}
	
	public int getType() {
		return TYPE;
	}
	
	public InputStream toStream() {
		return Stream.getStream(this);
	}

}
